package com.yanqu.road.server.cmd.minewar.task;

import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.minewar.UserMinePit;
import com.yanqu.road.pb.minewar.MineWarProto;
import com.yanqu.road.server.cmd.base.BaseTask;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.config.PatronsMgr;
import com.yanqu.road.server.manger.player.MineWarMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.PropertyHelper;

import java.math.BigInteger;

public class DetectUserPitDataTask extends BaseTask {

    private long userId;

    private int mineType;

    private int pitId;

    private int patronsCount;

    private BigInteger ability;

    public DetectUserPitDataTask(YanQuMessage packet, GamePlayer player) {
        super(packet, player);
    }

    @Override
    protected boolean parseData() throws Exception {
        MineWarProto.MineDetectUserMinePitReqMsg reqMsg = MineWarProto.MineDetectUserMinePitReqMsg.parseFrom(packet.getBytes());
        userId = reqMsg.getUserId();
        mineType = reqMsg.getMineType();
        pitId = reqMsg.getPitId();
        return true;
    }

    @Override
    protected void execute() {
        if(player.getUserId() == userId){
            ret = GameErrorCode.E_MINE_WAR_MINE_CAN_NO_DETECT_SELF_PIT;
            return;
        }
        //检测矿坑是否存在
        UserMinePit userMinePit = MineWarMgr.getUserMinePit(mineType, pitId);
        if(null == userMinePit){
            ret = GameErrorCode.E_MINE_WAR_MINE_TYPE_NO_FOUND;
            return;
        }
        if(userMinePit.getUserId() != userId){
            ret = GameErrorCode.E_MINE_WAR_MINE_PIT_OWNER_CHANGE;
            return;
        }
        //判断是否足够侦查道具
        if(!player.getModule(CurrencyModule.class).removeCurrency(PropertyHelper.parseStringToProperty(GameConfig.MINE_WAR_DETECT_CONSUME),
                eLogMoneyType.MineWar, eLogMoneyType.MineWarDetect)){
            ret = GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            return;
        }

        patronsCount = userMinePit.getPatronsIdList().size();
        //获取总实力
        ability = PatronsMgr.getPatronsListAbility(userId, userMinePit.getPatronsIdList());
    }

    @Override
    protected void sendData(GamePlayer player) {
        MineWarProto.MineDetectUserMinePitRespMsg.Builder respMsg = MineWarProto.MineDetectUserMinePitRespMsg.newBuilder();
        respMsg.setRet(ret);
        if(0 == ret){
            respMsg.setPatronsCount(patronsCount);
            respMsg.setTotalAbility(ability.longValue());
        }
        player.sendPacket(Protocol.U_MINE_WAR_DETECT_USER_PIT, respMsg);
    }
}
